滑动窗口的最大值

滑动窗口的最大值

题目描述

给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}; 针对数组{2,3,4,2,6,2,5,1}的滑动窗口有以下6个: {[2,3,4],2,6,2,5,1}, {2,[3,4,2],6,2,5,1}, {2,3,[4,2,6],2,5,1}, {2,3,4,[2,6,2],5,1}, {2,3,4,2,[6,2,5],1}, {2,3,4,2,6,[2,5,1]}。

  • 每次找到窗口中的最大值放进res中
  • 一次移动一格
  • i对应的是窗口尾部对应的数组下标
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function maxInWindows(num, size)
{
// write code here

const res=[]
const queue=[]
let max=-1;
let i=0;
if(num.length==0||size<1||size>num.length)return res;
while(size--){
queue.push(num[i])
if(max<=num[i]) max=num[i]
i++;
}
res.push(max)
while(i<num.length){
let m=queue.shift()
if(m==max){
max=getMax(queue)
}
queue.push(num[i])
if(num[i]>=max) max=num[i]
res.push(max)
i++;
}
return res
}
function getMax(q){
var max=-1
for(let j=0;j<q.length;j++){
if(q[j]>max){
max=q[j]
}
}
return max;
}